import 'package:expandable/expandable.dart';
import 'package:flutter/material.dart';
import 'package:x3_component_core/theme/expand_theme.dart';

class BaseFilterSelector extends StatefulWidget {
  final String title;
  final String selectedText;
  final bool isExpanded;
  final List<Widget> children;
  final List<Widget> collapsedChildren;
  final Function(bool) onChange;

  const BaseFilterSelector({
    Key key,
    @required this.title,
    @required this.children,
    this.isExpanded = false,
    this.selectedText,
    this.collapsedChildren,
    this.onChange,
  })  : assert(title != null),
        assert(children != null),
        super(key: key);
  @override
  _BaseFilterSelectorState createState() => _BaseFilterSelectorState();
}

class _BaseFilterSelectorState extends State<BaseFilterSelector> with AutomaticKeepAliveClientMixin {
  ExpandableController _expandableController;

  @override
  void initState() {
    _expandableController = ExpandableController(initialExpanded: widget.isExpanded);
    _expandableController.addListener(() {
      if (widget.onChange != null) widget.onChange(_expandableController.expanded);
    });
    super.initState();
  }

  @override
  void dispose() {
    _expandableController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ExpandablePanel(
      controller: _expandableController,
      theme: ExpandComponentsTheme.expandableThemeData,
      header: Container(
        height: 40,
        child: Row(
          children: [
            Container(margin: EdgeInsets.symmetric(horizontal: 12), child: Text(widget.title, style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14))),
            Expanded(
              child: Container(
                alignment: Alignment.centerRight,
                child: Text(widget.selectedText ?? '', overflow: TextOverflow.ellipsis),
              ),
            ),
          ],
        ),
      ),
      collapsed: widget.collapsedChildren != null ? _buildWrap(widget.collapsedChildren) : SizedBox(),
      expanded: _buildWrap(widget.children),
    );
  }

  Widget _buildWrap(List<Widget> children) {
    return Padding(
      padding: EdgeInsets.fromLTRB(12, 4, 12, 12),
      child: Wrap(spacing: 8, runSpacing: 8, children: children),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
